#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QDateTime>
#include <QFileDialog>
#include <QHostInfo>


bool TCP_Open=false;
bool Serial_Open=false;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->tabWidget->setStyleSheet(":/qss/tabWidget.qss");

    tcpServer = new QTcpServer(this);
    tcpSocket = new QTcpSocket(this);
    serialPort = new QSerialPort(); //新建一个用来与外界进行通信的串口接口
    windowInit();                   //基本设置初始化
    serialPortInit();               //串口初始化
    chartInit();
    openDb();

    //get_Ip();
    //getData("桂林");
    //默认使用主机模式，等待新的连接
    connect(&requst_ip,&QNetworkAccessManager::finished, this, &MainWindow::json_Ip);
    connect(&requst_city,&QNetworkAccessManager::finished, this, &MainWindow::json_City);
    connect(&requst_weather,&QNetworkAccessManager::finished, this, &MainWindow::json_Weather);

    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnection_Slot()));
    connect(ui->searchBt,SIGNAL(clicked()),this,SLOT(on_SearchBt_Clicked()));
    connect(ui->locateBt,SIGNAL(clicked()),this,SLOT(on_LocateBt_Clicked()));
    connect(ui->OpenBt,SIGNAL(clicked()), this, SLOT(on_OpenBt_Clicked()));
    connect(ui->CloseBt,SIGNAL(clicked()),this,SLOT(on_CloseBt_Clicker()));
    connect(ui->SendBt,SIGNAL(clicked()), this, SLOT(on_SendBt_Clicked()));
    connect(ui->ClearBt,SIGNAL(clicked()), this, SLOT(on_ClearBt_Clicked()));
    connect(ui->OutBt,SIGNAL(clicked()),this,SLOT(rcvDataOutputToFile()));

    connect(serialPort,SIGNAL(readyRead()),this,SLOT(receiveData()));
    connect(serialPort,SIGNAL(errorOccurred(QSerialPort::SerialPortError)),this,SLOT(handleSerialError(QSerialPort::SerialPortError)));
    connect(ui->comboBox_chooseCom,SIGNAL(clicked()),this,SLOT(comboBox_buadClicked()));
    connect(ui->comboBox_setBuad,SIGNAL(activated(int)),this,SLOT(setBuad(int)));
    connect(ui->SendBt_2,SIGNAL(clicked()),this,SLOT(sendData()));
    connect(ui->OpenBt_2,SIGNAL(clicked()),this,SLOT(openSerialport()));
    connect(ui->CloseBt_2,SIGNAL(clicked()),this,SLOT(closeSerialport()));
    connect(ui->ClearBt_2,SIGNAL(clicked()),this,SLOT(getData(QString)));
    connect(ui->OutBt_2,SIGNAL(clicked()),this,SLOT(rcvDataOutputToFile()));
    connect(ui->RefreshBt,SIGNAL(clicked()),this,SLOT(refreshCom()));

}
QString MainWindow::TEXT_COLOR(QString color,QString str){
    return "<font color= "+ color +">" + str + "</font> <font></font>";
}
void MainWindow::openDb(){
    db = QSqlDatabase::addDatabase("QSQLITE");

    db.setDatabaseName("E:/QtProject/Project_esp8266/test.sqlite");

    if (!db.open())
    {
        qDebug() << "Error: Failed to connect database." << db.lastError();
    }

}
//*****************************************************************TCP槽函数*****************************************************************//
void MainWindow::newConnection_Slot(){
    tcpSocket=tcpServer->nextPendingConnection();//得到通信的套接字对象
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));
    connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(disconnected_Slot()));

    ui->SendBt->setEnabled(true);
    ui->CloseBt->setEnabled(true);
}
void MainWindow::readyRead_Slot(){
    QByteArray receiveData;
    QSqlQuery sql_query;
    sql_query.prepare(insert_sql);
    count++;
    while(!tcpSocket->atEnd()){
        receiveData = tcpSocket->readAll();
    }
    if (!receiveData.isEmpty())
    {
        QStringList list = ((QString)receiveData).split(',');
        //显示有问题
        QString str=TEXT_COLOR("blue",QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"))+"《- ";
        QString str2 = str.append(receiveData);
        ui->RecvEdit->append(str2);
        //折线图更新
        // serie1->append(count,list[0].toFloat());
        // serie2->append(count,list[1].toFloat());
        // serie3->append(count,list[2].toFloat());
        // serie4->append(count,list[3].toFloat());

        // //保存到数据库中
        // sql_query.addBindValue(QDateTime::currentDateTime());
        // sql_query.addBindValue(list[0]);
        // sql_query.addBindValue(list[1]);
        // sql_query.addBindValue(list[2]);
        // sql_query.addBindValue(list[3]);
        // if(!sql_query.exec())
        // {
        //     qDebug()<<sql_query.lastError();
        // }
    }
    receiveData.clear();
}

void MainWindow::disconnected_Slot(){
    tcpSocket->close();
}
void MainWindow::on_OpenBt_Clicked()
{
    TCP_Open=true;
    tcpServer->listen(QHostAddress::Any,ui->PortEdit->toPlainText().toUInt());
}
void MainWindow::on_CloseBt_Clicked()
{
    tcpServer->close();
    tcpSocket->close();
    TCP_Open = false;
}
void MainWindow::on_SendBt_Clicked()
{
    if(TCP_Open){
        QString SendCon =  ui->SendEdit->toPlainText();
        if(SendCon!=""){
            if(ui->checkBox_sendNewLine->isChecked() == true)
            {
                QByteArray sendBuf = SendCon.toLocal8Bit();
                int cnt = sendBuf.size();
                sendBuf = sendBuf.insert(cnt,"\r\n");
                tcpSocket->write(sendBuf);
            }else{
                tcpSocket->write(ui->SendEdit->toPlainText().toLocal8Bit().data());
            }
            //整合符号 ->
            QString str=TEXT_COLOR("blue",QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")) +"-> ";
            QString str2 = str.append(SendCon);
            ui->RecvEdit->append(str2);
            //tcpSocket->write(ui->SendEdit->toPlainText().toLocal8Bit().data());
        }else
            QMessageBox::critical(this,"警告","不能发送空白信息");
    }else
        QMessageBox::critical(this,"提示","发送失败，网络尚未连接");
}
void MainWindow::on_ClearBt_Clicked()
{
    ui->SendEdit->clear();
}
//*****************************************************************串口函数*****************************************************************//
void MainWindow::windowInit()
{
    ui->SendBt->setEnabled(false);
    ui->CloseBt->setEnabled(false);
    ui->CloseBt_2->setEnabled(false);
    ui->OpenBt_2->setEnabled(false);
    ui->SendBt_2->setEnabled(false);
    lab_temp_range[0] = ui->label_8;
    lab_temp_range[1] =ui->label_11;
    lab_temp_range[2] =ui->label_13;
    lab_temp_range[3] =ui->label_15;
    lab_temp_range[4] =ui->label_22;
    lab_date[0] = ui->label_9;
    lab_date[1] = ui->label_10;
    lab_date[2] = ui->label_12;
    lab_date[3] = ui->label_14;
    lab_date[4] = ui->label_23;
    lab_weather_type_pic[0] = ui->label_16;
    lab_weather_type_pic[1] = ui->label_17;
    lab_weather_type_pic[2] = ui->label_18;
    lab_weather_type_pic[3] = ui->label_19;
    lab_weather_type_pic[4] = ui->label_24;
    map1.insert("暴雪","snwoy4");
    map1.insert("暴雨","rain4");
    map1.insert("冰雹","hail");
    map1.insert("大雪","snowy3");
    map1.insert("大雨","rain4");
    map1.insert("多云","cloudy1");
    map1.insert("雷阵雨","thunderrain");
    map1.insert("霾","haze");
    map1.insert("晴","sun");
    map1.insert("雾","vapor");
    map1.insert("小雪","snwoy1");
    map1.insert("小雨","rain1");
    map1.insert("阴","cloudy2");
    map1.insert("雨夹雪","snowyrain");
    map1.insert("中雪","snwoy2");
    map1.insert("中雨","rain2");


}
void MainWindow::serialPortInit(){
    refreshCom();
    ui->comboBox_setBuad->addItem("4800");
    ui->comboBox_setBuad->addItem("9600");
    ui->comboBox_setBuad->addItem("115200");
    ui->comboBox_setBuad->setCurrentIndex(1);
}
//刷新串口列表
void MainWindow::refreshCom()
{
    ui->comboBox_chooseCom->clear();
    foreach(QSerialPortInfo portInfo, QSerialPortInfo::availablePorts())
        ui->comboBox_chooseCom->addItem(portInfo.portName()+":"+portInfo.description());
    ui->OpenBt_2->setEnabled(ui->comboBox_chooseCom->count()>0);

}
//*****************************************************************串口槽函数*****************************************************************//
void MainWindow::setBuad(int buad)
{
    QString str = ui->comboBox_setBuad->currentText();
    serialPort->setBaudRate(str.toInt());
}
void MainWindow::clearRcv()
{
    ui->RecvEdit_2->clear();
}
void MainWindow::openSerialport()
{
    ui->CloseBt_2->setEnabled(true);
    ui->OpenBt_2->setEnabled(false);

    QList<QSerialPortInfo>  comList = QSerialPortInfo::availablePorts();
    QSerialPortInfo portInfo = comList.at(ui->comboBox_chooseCom->currentIndex());
    serialPort->setPort(portInfo);      //设置使用哪个串口

    if(serialPort->open(QIODevice::ReadWrite) == false)
    {
        QMessageBox::critical(NULL, "critical", "找不到串口/串口被占用", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        closeSerialport();
    }
    else
    {
        serialPort->setBaudRate(QSerialPort::Baud115200);
        serialPort->setDataBits(QSerialPort::Data8);
        serialPort->setParity(QSerialPort::NoParity);
        serialPort->setStopBits(QSerialPort::OneStop);
        serialPort->setFlowControl(QSerialPort::NoFlowControl);
        ui->SendBt_2->setEnabled(true);
        Serial_Open = true;
    }
}
void MainWindow::closeSerialport()
{
    if(serialPort->isOpen()){
        serialPort->clear();
        serialPort->close();
    }
    ui->CloseBt_2->setEnabled(false);
    ui->OpenBt_2->setEnabled(true);
}
void MainWindow::handleSerialError(QSerialPort::SerialPortError serialPortErr)
{
    if(serialPortErr == QSerialPort::ResourceError)
    {
        QMessageBox::critical(NULL, "critical", "设备拔出", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        closeSerialport();
    }
    if(serialPortErr == QSerialPort::DeviceNotFoundError)
    {
        QMessageBox::critical(NULL, "critical", "找不到串口", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        closeSerialport();
    }
}
void MainWindow::rcvDataOutputToFile()
{
    QFileDialog dlg(this);

    //获取内容的保存路径
    QString fileName = dlg.getSaveFileName(this, tr("Save As"), "./", tr("Text File(*.txt)"));

    if( fileName == "" )
    {
        return;
    }
    //内容保存到路径文件
    QFile file(fileName);
    //以文本方式打开
    if( file.open(QIODevice::WriteOnly | QIODevice::Text) )
    {
        QTextStream out(&file); //IO设备对象的地址对其进行初始化
        if(TCP_Open)out << ui->RecvEdit->toPlainText();
        if(Serial_Open)out << ui->RecvEdit_2->toPlainText();

        QMessageBox::warning(this, tr("Finish"), tr("Successfully save the file!"));

        file.close();
    }
    else
    {
        QMessageBox::warning(this, tr("Error"), tr("Fail to open file!"));
    }
}
//波特率选择comboBox点击的槽函数
void MainWindow::comboBox_buadClicked()
{
    refreshCom();
}
void MainWindow::sendData()
{
    if(serialPort->isOpen())
    {
        QString message = ui->SendEdit_2->toPlainText();
        serialPort->write(QByteArray::fromHex(message.toLatin1()));
    }
}
void MainWindow::receiveData()
{
    QByteArray message = serialPort->readAll();
    QString date = QDateTime::currentDateTime().toString("hh:mm:ss");       //获取当前时间
    QString data = QString::fromLocal8Bit(message);
    ui->RecvEdit_2->append(date+QString("->  ")+QString(data));
}
//*****************************************************************Chart函数*****************************************************************//
void MainWindow::chartInit(){

    ui->ChartView1->setChart(chart1);
    ui->ChartView1->setRenderHint(QPainter::Antialiasing);
    ui->ChartView2->setChart(chart2);
    ui->ChartView2->setRenderHint(QPainter::Antialiasing);

    serie1->setName("温度");
    serie2->setName("湿度");
    serie3->setName("光照强度");
    serie4->setName("土壤湿度");
    chart1->addSeries(serie1);
    chart1->addSeries(serie2);
    chart2->addSeries(serie3);
    chart2->addSeries(serie4);
    chart1->createDefaultAxes();
    chart2->createDefaultAxes();

}
//*****************************************************************定位及天气函数*****************************************************************//
void MainWindow::on_SearchBt_Clicked(){
    get_Weather(ui->CityEdit->text());
    ui->label_20->setText(ui->CityEdit->text() + "市");
}
void MainWindow::on_LocateBt_Clicked(){
    get_Ip();
}
void MainWindow::get_Ip(void)
{
    QNetworkRequest request;
    request.setUrl(QUrl("http://whois.pconline.com.cn/ipJson.jsp?json=true"));
    requst_ip.get(request);
}
void MainWindow::json_Ip(QNetworkReply *reply)
{
    QString all = reply->readAll();
    QJsonDocument jsonDocument = QJsonDocument::fromJson(all.toUtf8());
    QJsonObject jsonObject = jsonDocument.object();
    QString ip = jsonObject.value("ip").toString();
    reply->deleteLater();
    get_City(ip);
}
void MainWindow::get_City(QString ip)
{
    QNetworkRequest request;
    request.setUrl(QUrl(QString("https://apis.map.qq.com/ws/location/v1/ip?ip=%1&key=6LDBZ-BF4HK-G2ZJA-ABCNH-3A44S-7OFZI").arg(ip)));
    requst_city.get(request);
}
//json解析
void MainWindow::json_City(QNetworkReply *reply)
{
    QString all = reply->readAll();
    QJsonDocument jsonDocument = QJsonDocument::fromJson(all.toUtf8());
    if(!jsonDocument.isNull()){
     QJsonObject object = jsonDocument.object();
        if(object.contains("result")){
         QJsonValue result = object.value("result");
            if(result.isObject()){
             QJsonObject result_data = result.toObject();
                if(result_data.contains("ad_info"))
             {
                 QJsonValue ad_info = result_data.value("ad_info");
                    if(ad_info.isObject()){
                        QJsonObject ad_data = ad_info.toObject();
                        QString city = ad_data.value("city").toString();
                        ui->label_20->setText(city);
                        //调用天气数据申请
                        get_Weather(city.remove("市"));
                    }
             }
            }
        }
    }
    reply->deleteLater();
}
void MainWindow::get_Weather(QString city){
    QNetworkRequest request;
    request.setUrl(QUrl(QString("http://apis.juhe.cn/simpleWeather/query?city=%1&key=251518e073ef6c3c9504dd286c3f6a86").arg(city)));
    requst_weather.get(request);  //get请求头
}
void MainWindow::json_Weather(QNetworkReply *reply)
{

    QString all = reply->readAll();
    //qDebug()<<"recv weather data!!"<<all;

    QJsonParseError err;
    QJsonDocument json_recv = QJsonDocument::fromJson(all.toUtf8(),&err);//解析json对象
    qDebug() << err.error;
    if(!json_recv.isNull())
    {
        QJsonObject object = json_recv.object();

        if(object.contains("result"))
        {
            QJsonValue result = object.value("result");  // 获取指定 key 对应的 value
            if(result.isObject())
            {
                QJsonObject result_data = result.toObject();
                if(result_data.contains("realtime"))
                {
                    QJsonObject a = result_data.value("realtime").toObject();
                    ui->date->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd dddd"));
                    ui->lab_wendu->setText(a.value("temperature").toString() + "℃");
                    ui->humidy->setText(a.value("humidity").toString() + "%");
                    ui->direct->setText(a.value("direct").toString());
                    ui->power->setText(a.value("power").toString());
                    ui->aqi->setText(a.value("aqi").toString() + "ug/cm³");
                    QString info = a.value("info").toString();
                    ui->lab_weather_type->setText(info);
                    ui->lab_weather_type_pic->setMaximumSize(200,200);
                    ui->lab_weather_type_pic->setScaledContents(true);
                    ui->lab_weather_type_pic->setPixmap(QPixmap(QString(":/img/%1.png").arg(map1[info])));
                }
                if(result_data.contains("future")){
                    QJsonValue value = result_data.value("future");
                    QJsonObject day;
                    for(int i = 0;i < 5;i++){
                        day = value.toArray().at(i).toObject();
                        date[i] = day.value("date").toString();
                        temperature[i] = day.value("temperature").toString();
                        weather_type[i] = day.value("weather").toString();
                        // QJsonObject w = day.value("wid").toObject();
                        // wid[i] = "day:"+w.value("day").toString();
                        // wid[i].append("night:" + w.value("night").toString());
                        // direct[i] = day.value("direct").toString();
                    }
                }
            }
        }
    }
    else
    {
        qDebug()<<"请求数据失败";
    }
    reply->deleteLater(); //销毁请求对象
    data_Update();
}
void MainWindow::data_Update(){
    ui->label_21->setText(temperature[0]);
    for(int i = 0;i < 5;i++) {
        lab_weather_type_pic[i]->setMaximumSize(70,70);
        lab_weather_type_pic[i]->setScaledContents(true);
        QStringList parts = weather_type[i].split("转");
        if (parts.size() > 0) {
            lab_weather_type_pic[i]->setPixmap(QPixmap(QString(":/img/%1.png").arg(map1[parts[0]])));
        } else {
            lab_weather_type_pic[i]->setPixmap(QPixmap(QString(":/img/%1.png").arg(map1[weather_type[i]])));
        }
        lab_temp_range[i]->setText(temperature[i]);
        lab_date[i]->setText(date[i]);
    }
}
MainWindow::~MainWindow()
{
    delete ui;
}
